package com.example.taobao.ui.login;

import android.annotation.SuppressLint;
import android.app.Activity;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.taobao.MainActivity;
import com.example.taobao.R;
import com.example.taobao.bottomActivity;
import com.example.taobao.data.UserDataDpSQLHelp;
import com.example.taobao.data.userdata;
import com.example.taobao.databinding.MineFragmentBinding;
import com.example.taobao.ui.login.LoginViewModel;
import com.example.taobao.ui.login.LoginViewModelFactory;
import com.example.taobao.databinding.ActivityLoginBinding;

import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);
        TextView textview1 = (TextView) LayoutInflater.from(LoginActivity.this).inflate(R.layout.mine_fragment, null).findViewById(R.id.userDisplayName);
        TextView textview2 = (TextView) LayoutInflater.from(LoginActivity.this).inflate(R.layout.mine_fragment, null).findViewById(R.id.userVipName);
        final Button zhucbutton = binding.zcbut;
        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final Button loginButton = binding.login;
        final ProgressBar loadingProgressBar = binding.loading;

        zhucbutton.setEnabled(true);



        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {

                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled(loginFormState.isDataValid());
//                zhucbutton.setEnabled(loginFormState.isDataValid());
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });

        loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @SuppressLint("Range")
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {

                    String name = usernameEditText.getText().toString();
                    String password = passwordEditText.getText().toString();
                    BmobQuery<userdata> bmobQuery = new BmobQuery<userdata>();
                    bmobQuery.findObjects(new FindListener<userdata>() {
                        @Override
                        public void done(List<userdata> list, BmobException e) {
                            if(e==null){
//                                userdata userlogin = new userdata();
                                int i;
                                String gname;
                                String gpassword;
                                for (i=0;i<list.size();i++){
                                gname = list.get(i).getIphone().toString();
                                gpassword = list.get(i).getPassword().toString();

                                    if(gname.equals(name)&&!gpassword.equals(password)){
                                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                                        break;

                                    }
                                    if(gname.equals(name)&&gpassword.equals(password)){
                                        Toast.makeText(LoginActivity.this, "成功登入", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(LoginActivity.this, bottomActivity.class);
                                        String object = list.get(i).getObjectId();
                                        userdata p2 = new userdata();
                                        p2.setLoginZt(true);
                                        p2.update(object, new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {
                                                if(e==null){
                                                    Toast.makeText(LoginActivity.this, "已登入", Toast.LENGTH_SHORT).show();
                                                }else{
                                                    Toast.makeText(LoginActivity.this, "状态更新失败", Toast.LENGTH_SHORT).show();
                                                }
                                            }

                                        });

//                                        String vipname = list.get(i).getVipName().toString();
//                                        String username = list.get(i).getUsername().toString();
//                                        intent.putExtra("name",vipname);
//                                        intent.putExtra("vipname",username);
                                        startActivityForResult(intent,138);
                                        break;

                                    }
                                }
                                if(i==list.size()){
                                    Toast.makeText(LoginActivity.this, "账号不存在", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

                    UserDataDpSQLHelp DPBhelper = new UserDataDpSQLHelp(getApplicationContext());


                    updateUiWithUser(loginResult.getSuccess());
                }
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString());
                }
                return false;
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingProgressBar.setVisibility(View.VISIBLE);//显示进度条的
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        });

        zhucbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(LoginActivity.this, "ok", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivityForResult(intent,0);
            }
        });
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}
